Creating a Map in Python for Plotting

Import Libraries

  • Folium allows you to create interactive leaflet maps
  • Pandas allows for reading CSV files and turning it into a DataFrame
import folium
import pandas as pd

Read the Excel file

data = pd.read_excel("United_States_Offense_Type_by_Agency_2022.xlsx", sheet_name='Sheet2')
# data

Creating Dropdown

Import Libraries for Dropdown Widgets

import ipywidgets as widgets
from IPython.display import display

Options for Dropdown

Users have the option of selecting from - Total Offenses - Crimes Against Persons - Crimes Against Property - Crimes Against Society

They are required to select one of the options. If they don’t select any of them, the code will not run correctly.

options = ["Total\nOffenses", "Crimes\nAgainst\nPersons", "Crimes\nAgainst\nProperty", "Crimes\nAgainst\nSociety"]

Create the dropdown widget

dropdown = widgets.Dropdown(options=options, description='Filter:')

Define a function the handle the selection

Anytime a selection is made, the selection is shown as feedback to the user

def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        print("Selected:", change['new'])

Attach the function to the dropdown’s event handler

dropdown.observe(on_change)

Display the dropdown widget

display(dropdown)

Create a Map of the U.S.

Using folium library to create a map that starts the user looking at the U.S.

map_us = folium.Map(location=[37.0902, -95.7129], zoom_start=4, control_scale=True)

Creating the Map

We’re looping through the Excel data that was read earlier. We retrieve and store the longitude and latitude values of every city that appears in the Excel sheet. If there is a NaN value that appears in the data, it is skipped over.

Based on the selection made earlier in the dorpdown, the selection is assigned to the variable value. This basically tells folium what we want to see on the map.

We then use the CircleMarker function of the folium library to plot points upon the map. The size of the points being plotted is based on the corresponding values of dropdown selection.

for index, row in data.iterrows():
    #Location
    location = row['Location']
    #Latitude
    lat = row['Latitude']
    # if latitude is NaN
    if pd.isna(lat): 
        continue
    #Longitude
    lon = row['Longitude']
    
    # Value being displayed based on dropdown selection
    value = row[dropdown.value]
    folium.CircleMarker(location=[lat, lon], 
                        radius=value/5000, color='rgb(178,34,34)', 
                        fill=True, fill_color='rgb(178,34,34)', 
                        fill_opacity=0.3, 
                        weight=1,
                        tooltip=f"Location: {location} \n Value: {value}").add_to(map_us)

Display of Map

map_us
Make this Notebook Trusted to load map: File -> Trust Notebook